package com.example.ecommerce.mapper;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.ecommerce.entity.UserRole;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;
import java.util.stream.Collectors;

@Mapper
public interface UserRoleMapper extends BaseMapper<UserRole> {
    /**
     * 根据用户ID查询角色ID列表
     */
    default List<Long> selectRoleIdsByUserId(Long userId) {
        return selectList(new LambdaQueryWrapper<UserRole>()
                .eq(UserRole::getUserId, userId)
                .select(UserRole::getRoleId))
                .stream()
                .map(UserRole::getRoleId)
                .collect(Collectors.toList());
    }
    
    /**
     * 根据角色ID查询用户ID列表
     */
    default List<Long> selectUserIdsByRoleId(Long roleId) {
        return selectList(new LambdaQueryWrapper<UserRole>()
                .eq(UserRole::getRoleId, roleId)
                .select(UserRole::getUserId))
                .stream()
                .map(UserRole::getUserId)
                .collect(Collectors.toList());
    }
    
    /**
     * 批量插入用户角色关系
     */
    default void insertBatch(List<UserRole> userRoles) {
        if (userRoles != null && !userRoles.isEmpty()) {
            userRoles.forEach(this::insert);
        }
    }
    
    /**
     * 删除用户的所有角色关系
     */
    default void deleteByUserId(Long userId) {
        delete(new LambdaQueryWrapper<UserRole>()
                .eq(UserRole::getUserId, userId));
    }
    
    /**
     * 删除角色的所有用户关系
     */
    default void deleteByRoleId(Long roleId) {
        delete(new LambdaQueryWrapper<UserRole>()
                .eq(UserRole::getRoleId, roleId));
    }
    
    /**
     * 检查用户是否有指定角色
     */
    default boolean existsUserRole(Long userId, Long roleId) {
        return exists(new LambdaQueryWrapper<UserRole>()
                .eq(UserRole::getUserId, userId)
                .eq(UserRole::getRoleId, roleId));
    }
} 